#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int argc,char* argv[])
{
	if(argc < 3)
	{
		printf("incrrect parameter\n");
		return 1;
	}
	/*
 	 * 1. 创建socket，要创建UDP类型的socket，广播包是用UDP发送的
 	 */
	int server_fd = socket(AF_INET,SOCK_DGRAM,0);
	
	/*
 	 * 2. 设置要发送到的广播域和port
 	 */
	struct sockaddr_in des_sock_attr;
	des_sock_attr.sin_family = AF_INET;
	// 注意argv[1]是广播地址
	inet_pton(AF_INET,argv[1],&des_sock_attr.sin_addr.s_addr);
	des_sock_attr.sin_port = htons((short)atoi(argv[2]));

	/*
 	 * 2. 设置socket选项，使socket可以发送广播报
 	 */
	int opt = 1;
	setsockopt(server_fd,SOL_SOCKET,SO_BROADCAST,&opt,sizeof(int));
	char buf[512] = {'\0'};
	int i = 0;
	while(1)
	{
		sprintf(buf,"message %d\n",i);
		if(0 >= sendto(server_fd,buf,sizeof(buf),0,(struct sockaddr*)&des_sock_attr,sizeof(des_sock_attr)))
		{
			perror("sendto");
			continue;
		}
		printf("broadcast : %d\n",i);
		sleep(3);
		i++;
		memset(buf,'\0',sizeof(buf));
	}
	return 1;
}
